package com.hs.mod_archive.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import com.hs.framework.base.BaseDataBindFragment
import com.hs.framework.toast.TipsToast
import com.hs.mod_archive.R
import com.hs.mod_archive.databinding.DialogEditArchiveBinding
import com.hs.mod_archive.databinding.FragmentArchiveStatusManagementBinding
import com.hs.mod_archive.helper.ArchiveStatusManagerHelper
import com.hs.mod_archive.helper.ArchiveStatusManagerHelper.OnItemClickListener
import com.hs.mod_archive.helper.ListViewHelper
import com.hs.mod_archive.helper.ListViewHelper.Companion.perPageCount
import com.hs.mod_archive.view.DialogUtil
import com.hs.mod_archive.view.MyDialog
import com.hs.room.model.archive.ArchiveStatus
import com.hs.room.repository.service.IArchiveDictRepository
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class FragmentArchiveStatusManagement :
    BaseDataBindFragment<FragmentArchiveStatusManagementBinding>() {

    @Inject
    lateinit var service: IArchiveDictRepository

    private var types: List<ArchiveStatus>? = null
    var mDialog: MyDialog? = null
    lateinit var helper: ArchiveStatusManagerHelper
    var dialogEditArchiveStatusBinding: DialogEditArchiveBinding? = null
    override fun initView(view: View, savedInstanceState: Bundle?) {
        mBinding!!.btAdd.setOnClickListener { showDialogEdit(null) }

        helper =
            ArchiveStatusManagerHelper(mBinding!!.footPageListView, object : OnItemClickListener {
                override fun onItemClickEdit(entity: ArchiveStatus?, position: Int) {
                    showDialogEdit(entity)
                }

                override fun onItemClickDelete(entity: ArchiveStatus?, position: Int) {
                    del(entity!!)
                }
            }, object : ListViewHelper.FootSearchCallback {
                override fun onActionSearch(index: Int) {
                    goPage(index)
                }
            })


    }


    private fun goPage(i: Int) {
        lifecycleScope.launch {
            service.getStatus(i, perPageCount).collect {
                types = it
                helper.setListDataAndRefresh(it)
            }
        }
    }


    private fun del(d: ArchiveStatus) {
        lifecycleScope.launch {
            service.delete(d)
            TipsToast.showTips("删除成功")
        }
    }


    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            val count = service.countStatus()
            if (count < 1) {
                val arrayList = ArrayList<ArchiveStatus>()
                resources.getStringArray(R.array.archiveStatus).forEach { i ->
                    run {
                        val item = ArchiveStatus(0, 0, i, "", 0, "", true)
                        service.insert(item);
                        arrayList.add(item)
                    }
                }
                helper.setFootValue(arrayList.size, 0)
            } else {
                helper.setFootValue(count, 0)
            }
        }
        goPage(0)
    }

    private fun showDialogEdit(mArchiveStatus: ArchiveStatus?) {

        //-------------------------
        if (null == dialogEditArchiveStatusBinding) {
            dialogEditArchiveStatusBinding = DialogEditArchiveBinding.inflate(layoutInflater)
        }
        dialogEditArchiveStatusBinding!!.tvTitle.setText(R.string.addStatus)
        dialogEditArchiveStatusBinding!!.btSubmit.setOnClickListener { _ ->
            val name: String = dialogEditArchiveStatusBinding!!.etNameOfValue.text.toString().trim()
            if (TextUtils.isEmpty(name)) {
                TipsToast.showTips("请输入有效的名称")
                return@setOnClickListener
            }
            val ob: Boolean =
                dialogEditArchiveStatusBinding!!.spinnerEnable.selectedItemPosition == 0
            submitName(
                mArchiveStatus,
                name,
                dialogEditArchiveStatusBinding!!.etRemark.text.toString().trim(), ob
            )
        }
        val root: ConstraintLayout = dialogEditArchiveStatusBinding!!.getRoot()
        val parent = root.parent
        if (null != parent) {
            val viewGroup = parent as ViewGroup
            viewGroup.removeView(root)
            dialogEditArchiveStatusBinding!!.etNameOfValue.setText("")
            dialogEditArchiveStatusBinding!!.spinnerEnable.setSelection(0)
            dialogEditArchiveStatusBinding!!.etRemark.setText(null)
        }
        if (null != mArchiveStatus) {
            dialogEditArchiveStatusBinding!!.etNameOfValue.setText(mArchiveStatus!!.asName)
            dialogEditArchiveStatusBinding!!.etRemark.setText(mArchiveStatus.asRemarks)
            if (mArchiveStatus.enable) {
                dialogEditArchiveStatusBinding!!.spinnerEnable.setSelection(0)
            } else {
                dialogEditArchiveStatusBinding!!.spinnerEnable.setSelection(1)
            }
        }
        dialogEditArchiveStatusBinding!!.tvTitle.setText(if (null != mArchiveStatus) R.string.edit else R.string.add)
        dialogEditArchiveStatusBinding!!.tvNameOf.setText(R.string.name)
        dialogEditArchiveStatusBinding!!.btClose.setOnClickListener { _ -> dismissDialogEdit() }
        dialogEditArchiveStatusBinding!!.btCancel.setOnClickListener { _ -> dismissDialogEdit() }
        //-------------------------
        val w = resources.getDimensionPixelSize(R.dimen.dp_582)
        val h = resources.getDimensionPixelSize(R.dimen.dp_382)
        mDialog = DialogUtil.buildSpecialView(activity, root, w, h, false, false)
    }

    fun dismissDialogEdit() {
        mDialog?.dismiss()
        mDialog = null
        dialogEditArchiveStatusBinding = null
    }

    private fun submitName(
        src: ArchiveStatus?,
        name: String,
        remark: String,
        enabled: Boolean
    ) {
        // 编辑已有的
        if (null != src) {
            if (name != src.asName) {
                for (entity in types!!) {
                    // 同名更新 删除 替换
                    if (name == entity.asName) {
                        TipsToast.showTips("名称已存在，请重新输入")
                        return
                    }
                }
            }
            src.asName = name
            src.asRemarks = remark
            src.enable = enabled
            update(src)
        } else {
            if (null != types) {
                for (entity in types!!) {
                    if (name == entity.asName) {
                        TipsToast.showTips("名称已存在，请重新输入")
                        return
                    }
                }
            }
            var fileType =
                ArchiveStatus(0, 0, name, remark, 0, "", enabled)
            insert(fileType)
        }
        dismissDialogEdit()
    }

    fun update(src: ArchiveStatus) {
        lifecycleScope.launch {
            service.update(src)
        }
    }

    fun insert(src: ArchiveStatus) {
        lifecycleScope.launch {
            service.insert(src)
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        helper.onDestroyView()
    }
}
